import React, { useRef, useState, useEffect } from 'react';
import {
  View,
  Dimensions,
  StyleSheet,
  Text,
  TextInput,
  Keyboard,
} from 'react-native';
import Pdf from "react-native-pdf";

export default function PdfExample() {
  const localSource = require("../assets/pdfPassword.pdf");
  const spacing = 10;
  const scale = 1;
  const password = '74108520';
  const page = 0;
  const minScale = 0.5;
  const maxScale = 5;
  const fitPolicy = 1;
  const [pageCount, setPageCount] = useState(0);
  const [pageNum, setPageNum] = useState('1');
  const [currentPage, setCurrentPage] = useState(1);
  const [keyboardHeight, setKeyboardHeight] = useState(0);
  const [showInvalidHint, setShowInvalidHint] = useState(false);
  const pdfRef = useRef(null);

  // 监听键盘事件
  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      event => {
        setKeyboardHeight(event.endCoordinates.height);
      },
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        setKeyboardHeight(0);
      },
    );

    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);
  return (
    <View style={styles.sectionContainer}>
       <View
        style={[
          styles.btnContainer,
          { bottom: keyboardHeight > 0 ? keyboardHeight : 0 },
        ]}>
        <Text style={{ color: 'white', fontSize: 16, marginRight: 10 }}>
          页码
        </Text>
        <TextInput
          value={pageNum}
          style={styles.textInputStyle}
          selectionColor="white"
          onChangeText={text => {
            setPageNum(text);
          }}
          onBlur={e => {
            if (pdfRef.current) {
              const text = e.nativeEvent.text;
              let num = Number(text);
              if (isNaN(num)) {
                setShowInvalidHint(true);
                return;
              }
              (pdfRef.current as any).setPage(num);
              if (num < 1 || num > pageCount) {
                setPageNum(currentPage.toString());
                return;
              }
              showInvalidHint && setShowInvalidHint(false);
            }
          }}
        />
        <Text style={{ color: 'white', fontSize: 16 }}>/ {pageCount}</Text>
        {showInvalidHint && (
          <Text style={{ color: 'red', fontSize: 12, position: 'absolute', right: 25, transform: [{ translateY: -26 }] }}>请输入有效页码</Text>
        )}
      </View>
      <Pdf
        ref={pdfRef}
        source={localSource}
        style={styles.pdf}
        spacing={spacing}
        scale={scale}
        password={password}
        page={page}
        minScale={minScale}
        maxScale={maxScale}
        fitPolicy={fitPolicy}
        onError={(error) => {
          console.log(`onError parameter of error: ${error}`);
        }}
        onLoadComplete={(numberOfPages, filePath) => {
          console.log(`onLoadComplete parameter of numberOfPages: ${numberOfPages}`);
          console.log(`onLoadComplete parameter of filePath: ${filePath}`);
          setPageCount(numberOfPages);
        }}
        onLoadProgress={(percent) => {
          console.log(`onLoadProgress parameter of percent: ${percent}`);
        }}
        onPageChanged={(page, numberOfPages) => {
          console.log(`onPageChanged parameter of page: ${page}`);
          console.log(`onPageChanged parameter of numberOfPages: ${numberOfPages}`);
          setPageNum(page.toString());
          setCurrentPage(page);
        }}
        onScaleChanged={(scale) => {
          console.log(`onScaleChanged parameter of scale: ${scale}`);
        }}
        onPressLink={(uri) => {
          console.log(`onScaleChanged parameter: ${uri}`);
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  sectionContainer: {
    flex: 1,
    justifyContent: "flex-start",
    alignItems: "center",
  },
  pdf: {
    flex: 1,
    width: Dimensions.get("window").width,
    height: Dimensions.get("window").height,
  },
  btnContainer: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    height: 120,
    backgroundColor: '#3c3c3c',
    left: 0,
    right: 0,
    bottom: 0,
    paddingBottom: 50,
    zIndex: 9999,
    transitionProperty: 'bottom',
    transitionDuration: '300ms',
    transitionTimingFunction: 'ease-in-out',
  },
  textInputStyle: {
    width: 30,
    height: 25,
    backgroundColor: 'black',
    textAlign: 'center',
    color: 'white',
    marginRight: 5,
  },
});
